import router from "./index.js";
import useAuths from "@/hooks/useAuths"; // get token from cookie
import userStore from "@/store/userStore";
import bootstrap from "../bootstrap";

const whiteList = ["/login", "/404"]; // 不进行跳转检查白名单
let load = 0; //定义变量判断是否已经动态添加过，如果刷新后load永远为 0

// 给有权限的菜单添加路由
const addRoutesFun = (menu) => {
  menu.forEach((itemRouter) => {
    router.addRoute(itemRouter);
  });
  router.addRoute({
    path: "/:catchAll(.*)",
    redirect: "/404",
    name: "NotFound",
  });
};

router.beforeEach(async (to, from, next) => {
  const store = userStore();
  const { getToken, logoutFun, getAccessMenus } = useAuths();
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      // 已经登录跳转首页
      next({ path: "/home" });
    } else {
      const { hasInitAsyncRoutes, isListenDataLoop, accessMenus } = store;
      // 用于第一次进系统时调用signalr 实时通讯
      if (!isListenDataLoop) {
        store.setListenFlag(false);
        // bootstrap();
      }
      if (hasInitAsyncRoutes) {
        // 刷新时动态路由丢失
        if (load === 0 && to.name !== "Login") {
          load++;
          if (accessMenus.length === 0) {
            logoutFun();
            next({ path: "/login?iserror=1&unTourist=true" });
          } else {
            // 刷新时重新注册一遍路由的component
            const newTreeMenus = await getAccessMenus();
            // 给有权限的菜单添加路由
            addRoutesFun(newTreeMenus);
            next({ ...to, replace: true });
          }
        } else {
          next();
        }
      } else {
        // 登录成功后第一次跳转 初始化路由
        store.setInitRoutes(true);
        try {
          if (accessMenus.length === 0) {
            logoutFun();
            next({ path: "/login?iserror=1&unTourist=true" });
          } else {
            // 给有权限的菜单添加路由
            addRoutesFun(accessMenus);
            next({ ...to, replace: true });
          }
        } catch (error) {
          logoutFun();
          next({ path: "/login?iserror=1&unTourist=true" });
        }
      }
    }
  } else {
    /* 未存token */

    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}&unTourist=true`);
    }
  }
});
